/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.convert.vienna.util;

import at.schauer.gregor.vienna.convert.vienna.base.SeparatorConverter;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Gregor Schauer
 */
public class RandomConverter implements SeparatorConverter<Random> {
	@Override
	public Random sourceToTarget(String source, Class<? extends Random> targetClass) {
		try {
			String[] args = source.split(getSeparator());
			Random random = new Random();
			AtomicLong atomicLong = (AtomicLong) FieldUtils.readField(random, "seed", true);
			atomicLong.set(Long.parseLong(args[0]));
			FieldUtils.writeField(random, "nextNextGaussian", Double.parseDouble(args[1]), true);
			FieldUtils.writeField(random, "haveNextNextGaussian", Boolean.parseBoolean(args[2]), true);
			return random;
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String targetToSource(Random target) {
		try {
			AtomicLong seed = (AtomicLong) FieldUtils.readField(target, "seed", true);
			Double nextNextGaussian = (Double) FieldUtils.readField(target, "nextNextGaussian", true);
			Boolean haveNextNextGaussian = (Boolean) FieldUtils.readField(target, "haveNextNextGaussian", true);
			return String.format("%d%s%s%s%s", seed.get(), getSeparator(), nextNextGaussian, getSeparator(), haveNextNextGaussian);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String getSeparator() {
		return "_";
	}
}
